#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 100
#define NUM 100


char* argv[SIZE];
char command_line[NUM];
int main()
{
  while(1)
  {
  //1.首先输出系统及目录名称
    printf("[%s@%s %s]# ",getenv("USER"),getenv("HOSTNAME"),"myshell");
    fflush(stdout);
  
  //2.输入  
    memset(command_line,'\0',sizeof(char)*NUM);
    fgets(command_line,NUM,stdin);
    //由于输入会包含回车，导致多了一个字符
    command_line[strlen(command_line)-1] = '\0'; 
  
  //3.识别分离字符串
    argv[0] = strtok(command_line," ");
    int i = 1;
    while(argv[i++]=strtok(NULL," "));//最后的NULL也会被弄进去，刚好符合结束符
    
    //测试
    //int j = 0;
    //for(j;j<i;j++)
    //{
    //  printf("%d %s\n",j,argv[j]);
    //}
    
  //4.TODO
  

  //5.进程创建，终止，等待，替换
    pid_t id = fork();
    if(id==0)
    {
      //chlid,进行进程替换
      execvp(argv[0],argv); 
      exit(-1);
    }
    int status = 0;
    int ret = waitpid(id,&status,0);
    if(WIFEXITED(status))//正常终止信号是0，为真
    {
      printf("执行及等待成功，退出码为%d\n",WEXITSTATUS(status));
      //printf("退出码%d，退出信号%d\n",(status>>8)&0xFF,status&0x7F);
    }
    else
    {
      printf("等待出错\n");
    }
  }
  return 0;
}
